package cn.edu.lingnan.repository;

import cn.edu.lingnan.bean.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Repository
//JpaSpecificationExecutor ：一般要和 Repository体系的接口一起使用，用于动态生成Query来满足业务中各种复杂场景
public interface BookRepository extends JpaRepository<Book,Integer>, JpaSpecificationExecutor<Book> {
    //方法名称命名查询

    //更加Id 和 书名 进行查询
    //select * form book where id=? and name=?
    public Book findByIdAndName(int id,String name);

    //根据书名进行模糊查询
    public List<Book> findByNameLike(String name);

    //基于注解查询方式 //使用JPQL语句查询，基于实体类的查询来进行数据库表的映射

    @Modifying
    @Query("update Book b  set b.name = ?1,b.author = ?2 , b.price = ?3, b.sales = ?4, " +
            "b.stocks = ?5, b.imgPath = ?6, b.createTime = ?7 where b.id = ?8 ")
    int updateBookById(String name, String author, double price, int sales,int stocks,String imgPath,String createTime,int id);

    //@Modifying
    //@Query(value = "insert into Book(name,author) values(?1,?2)")
    //int insertBook(String name,String author);
    //jpql 不支持insert操作，需使用 save 操作替代

    /**
     * sql 语句中传参的两种方式
     *  1、使用？,后面紧跟数字序列；
     *  2、使用：，紧跟参数名，用@param注解标识
     */



   // public Book findByIdAndName2(int id,String name);

    @Query(value = "select * from Book where id= :id and name= :name",nativeQuery = true)
    Book findByIdAndName2 (@Param("id") int id, @Param("name") String name);
    //
    //Page<Book> findAll(Sort pageable);


    //批量删除
    @Modifying
    @Transactional
    @Query(value = "delete from Book where id in (:ids)")
    void deleteBatchById(@Param("ids") int[] ids);





}
